﻿using Microsoft.AspNetCore.Authorization;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using Volo.Abp.Identity;
using Volo.Abp.ObjectMapping;
using Volo.Abp;

namespace Wuther.Infrastructure.Organizations
{
    /// <summary>
    /// 人员单位关系接口实现
    /// </summary>
    [RemoteService(IsEnabled = false)]
    public class OrganizationUsersAppService : CrudAppService<
         OrganizationUsers,
         OrganizationUsersDto,
         Guid,
         GetOrganizationUsersInput,
         CreateOrUpdateOrganizationUsersDto,
         CreateOrUpdateOrganizationUsersDto>, IOrganizationUsersAppService
    {
        private readonly IRepository<IdentityUser, Guid> _identityUserRepository;
        private readonly IRepository<Organization, Guid> _organizationRepository;
        public OrganizationUsersAppService(IRepository<OrganizationUsers, Guid> repository, IRepository<IdentityUser, Guid> identityUserRepository, IRepository<Organization, Guid> organizationRepository)
            : base(repository)
        {
            _identityUserRepository = identityUserRepository;
            _organizationRepository = organizationRepository;
        }

        #region 设置查询条件
        /// <summary>
        /// 设置查询条件
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        protected async override Task<IQueryable<OrganizationUsers>> CreateFilteredQueryAsync(GetOrganizationUsersInput input)
        {
            return (await Repository.GetQueryableAsync()).WhereIf(input.UserId.HasValue, w => w.UserId == input.UserId)
                .WhereIf(input.OrganizationId.HasValue, w => w.OrganizationId == input.OrganizationId)
                .WhereIf(input.TenantId.HasValue, w => w.TenantId == input.TenantId);
        }
        #endregion



        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async override Task<PagedResultDto<OrganizationUsersDto>> GetListAsync(GetOrganizationUsersInput input)
        {
            var query = await CreateFilteredQueryAsync(input);
            var totalCount = await query.CountAsync();
            var list = query.AsNoTracking().OrderByDescending(x=>x.CreationTime).PageBy(input.SkipCount, input.MaxResultCount).ToList();
            return new PagedResultDto<OrganizationUsersDto>()
            {
                TotalCount = totalCount,
                Items = ObjectMapper.Map<List<OrganizationUsers>, List<OrganizationUsersDto>>(list)
            };
        }
         /// <summary>
        /// 获取列表（不分页）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>

        public async Task <List<OrganizationUsersDto>> GetAllListAsync(GetOrganizationUsersInput input)
        {
            var query = await CreateFilteredQueryAsync(input);
            var list = query.AsNoTracking().OrderByDescending(x => x.CreationTime).ToList();

            var info = ObjectMapper.Map<List<OrganizationUsers>, List<OrganizationUsersDto>>(list);

            if (info.Count > 0)
            {
                var userList = await _identityUserRepository.GetListAsync(g => info.Select(s => s.UserId).Contains(g.Id));
                var orgList = await _organizationRepository.GetListAsync();
                info.ForEach(item =>
                {
                    item.UserName = userList.FirstOrDefault(f => f.Id == item.UserId).UserName;
                    item.OrganizationName = orgList.FirstOrDefault(f => f.Id == item.OrganizationId)?.DisplayName;
                });
            }
            return info;
        }
    }
}
